package com.anjiplus.template.gaea.business.modules.https.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper;
import com.anji.plus.gaea.exception.BusinessExceptionBuilder;
import com.anji.plus.gaea.holder.UserContentHolder;
import com.anji.plus.gaea.utils.GaeaBeanUtils;
import com.anjiplus.template.gaea.business.code.ResponseCode;
import com.anjiplus.template.gaea.business.modules.dataset.service.DataSetService;
import com.anjiplus.template.gaea.business.modules.datasettransform.service.DataSetTransformService;
import com.anjiplus.template.gaea.business.modules.httpdatasettransform.controller.dto.HttpDataSetTransformDto;
import com.anjiplus.template.gaea.business.modules.httpdatasettransform.dao.entity.HttpDataSetTransform;
import com.anjiplus.template.gaea.business.modules.httpdatasettransform.service.HttpDataSetTransformService;
import com.anjiplus.template.gaea.business.modules.httppath.controller.dto.HttpPathDto;
import com.anjiplus.template.gaea.business.modules.httppath.service.HttpPathService;
import com.anjiplus.template.gaea.business.modules.https.controller.dto.HttpDto;
import com.anjiplus.template.gaea.business.modules.https.dao.HttpMapper;
import com.anjiplus.template.gaea.business.modules.https.dao.entity.Http;
import com.anjiplus.template.gaea.business.modules.https.service.HttpService;
import com.anjiplus.template.gaea.business.modules.httptotransform.dao.entity.HttpToTransform;
import com.anjiplus.template.gaea.business.modules.httptotransform.service.HttpToTransformService;
import com.anjiplus.template.gaea.business.util.RestTemplateUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Raod
 * @desc Http 数据集服务实现
 * @date 2021-03-18 12:11:31.150755900
 **/
@Service
//@RequiredArgsConstructor
@Slf4j
public class HttpServiceImpl implements HttpService {

    @Autowired
    private HttpMapper HttpMapper;

    @Autowired
    private DataSetService dataSetService;
    @Autowired
    private HttpPathService httpPathService;
    @Autowired
    private HttpToTransformService httpToTransformService;
    @Autowired
    private HttpDataSetTransformService httpDataSetTransformService;
    @Autowired
    private DataSetTransformService dataSetTransformService;


    @Override
    public GaeaBaseMapper<Http> getMapper() {
        return HttpMapper;
    }

    /**
     * 单条详情
     *
     * @param id
     * @return
     */
    @Override
    public HttpDto detailSetById(String id) {
        HttpDto dto = new HttpDto();
        Http result = selectOne(id);
        GaeaBeanUtils.copyAndFormatter(result, dto);
        return getDetailSet(dto);
    }

    /**
     * 单条详情
     *
     * @param setCode
     * @return
     */
    @Override
    public HttpDto detailSet(String setCode) {
        HttpDto dto = new HttpDto();
        Http result = selectOne("set_code", setCode);
        GaeaBeanUtils.copyAndFormatter(result, dto);
        return getDetailSet(dto);
    }

    public HttpDto getDetailSet(HttpDto dto) {
        //查询参数

        return dto;
    }


    /**
     * 新增数据集、添加查询参数、数据转换
     *
     * @param dto
     */
    @Override
    @Transactional
    public HttpDto insertSet(HttpDto dto) {
        String username = UserContentHolder.getContext().getUsername();
        dto.setCreateBy(username);
        dto.setCreateTime(new Date());

        Http dataSet = new Http();
        BeanUtils.copyProperties(dto, dataSet);
        //添加http接口相关
        insert(dataSet);
        if (!CollectionUtils.isEmpty(dto.getHttpDataSetTransformDtoList())) {
            //添加数据集
            List<HttpDataSetTransformDto> httpDataSetTransformDtoList = dto.getHttpDataSetTransformDtoList();

            for (HttpDataSetTransformDto httpDataSetTransformDto : httpDataSetTransformDtoList) {
                //添加数据集
                HttpDataSetTransform httpDataSetTransform = new HttpDataSetTransform();
                BeanUtils.copyProperties(httpDataSetTransformDto, httpDataSetTransform);
                httpDataSetTransformService.insert(httpDataSetTransform);

                String httpId = dataSet.getId();
                String dataSetTransformId = httpDataSetTransform.getId();
                //关联http和数据集
                HttpToTransform httpToTransform = new HttpToTransform();
                httpToTransform.setSetTransformId(dataSetTransformId);
                httpToTransform.setHttpId(httpId);
                httpToTransformService.insert(httpToTransform);
            }


        }


        return dto;
    }

    /**
     * 更新数据集、添加查询参数、数据转换
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSet(HttpDto dto) {
        if (StringUtils.isEmpty(dto.getId())) {
            throw new RuntimeException("修改失败!");
        }
        String username = UserContentHolder.getContext().getUsername();
        dto.setUpdateBy(username);
        dto.setUpdateTime(new Date());
        //1.更新数据集
        Http dataSet = new Http();
        BeanUtils.copyProperties(dto, dataSet);
        update(dataSet);
        //先清空中间表
        //2.删除中间表数据
        List<HttpToTransform> toTransforms = httpToTransformService.getByHttpId(dto.getId());
        if (!CollectionUtils.isEmpty(toTransforms)) {
            for (HttpToTransform toTransform : toTransforms) {
                String dataSetId = toTransform.getSetTransformId();
                //删除javaBean解析数据
                httpDataSetTransformService.deleteById(dataSetId);
            }
            //删除中间表数据
            httpToTransformService.deleteByHttpId(dto.getId());
        }

        //更新 http
        if (!CollectionUtils.isEmpty(dto.getHttpDataSetTransformDtoList())) {
            //添加数据集
            List<HttpDataSetTransformDto> httpDataSetTransformDtoList = dto.getHttpDataSetTransformDtoList();

            for (HttpDataSetTransformDto httpDataSetTransformDto : httpDataSetTransformDtoList) {
                //添加数据集
                HttpDataSetTransform httpDataSetTransform = new HttpDataSetTransform();
                BeanUtils.copyProperties(httpDataSetTransformDto, httpDataSetTransform);
                httpDataSetTransformService.insert(httpDataSetTransform);

                String httpId = dataSet.getId();
                String dataSetTransformId = httpDataSetTransform.getId();
                //关联http和数据集
                HttpToTransform httpToTransform = new HttpToTransform();
                httpToTransform.setSetTransformId(dataSetTransformId);
                httpToTransform.setHttpId(httpId);
                httpToTransformService.insert(httpToTransform);
            }


        }

    }


    /**
     * 删除数据集、添加查询参数、数据转换
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSet(String id) {
        //1.删除数据集
        deleteById(id);
        //2.删除中间表数据
        List<HttpToTransform> toTransforms = httpToTransformService.getByHttpId(id);
        if (!CollectionUtils.isEmpty(toTransforms)) {
            for (HttpToTransform toTransform : toTransforms) {
                String dataSetId = toTransform.getSetTransformId();
                //删除javaBean解析数据
                httpDataSetTransformService.deleteById(dataSetId);
            }
            //删除中间表数据
            httpToTransformService.deleteByHttpId(id);
        }
    }

    /**
     * 获取所有数据集
     *
     * @return
     */
    @Override
    public List<Http> queryAllDataSet(String dirId) {
        LambdaQueryWrapper<Http> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Http::getDirId, dirId);
        return HttpMapper.selectList(wrapper);
    }

    @Override
    public void copy(HttpDto dto) {
        if (null == dto.getId()) {
            throw BusinessExceptionBuilder.build(ResponseCode.NOT_NULL, "id");
        }
        Http dataSet = selectOne(dto.getId());
        Http dateSetCopy = copyDataSet(dataSet);
        insert(dateSetCopy);
    }

    @Override
    public Object sendRequest(HttpDto dto, HttpServletResponse response) {
        HashMap<Object, Object> hashmap = new HashMap<>();

        //是否解析处理结果
        List<HttpDataSetTransformDto> httpTransform = httpDataSetTransformService.getByHttpId(dto.getId());

        //方法转大写
        String method = dto.getMethod().toUpperCase();
        String url = dto.getUrl();
        //菜单栏 请求头 参数
        String menus = dto.getMenus();
        JSONObject jsonObject = JSONObject.parseObject(menus);

        //获取请求头
        JSONObject headers = jsonObject.getJSONObject("headers");
        Map<String, String> header = new HashMap<>();
        if (!CollectionUtils.isEmpty(headers)) {
            headers.forEach((key, value) -> header.put(key, value.toString()));
            RestTemplateUtils.setHeader(header);
        }

        JSONObject params = jsonObject.getJSONObject("params");


        //获取body参数
        JSONObject body = jsonObject.getJSONObject("body");
        //formdata
        JSONObject formData = body.getJSONObject("formData");
        //body中的json参数
        String bodyJSONArray = body.getString("json");

        //加入前置url拼接和请求头拼接
        if (!StringUtils.isEmpty(dto.getHttpPathId())) {
            HttpPathDto httpPathDto = httpPathService.getById(dto.getHttpPathId());
            if (!Objects.isNull(httpPathDto)) {
                String pathUrl = httpPathDto.getPathUrl();
                //加上前置http://xxx.com
                url = pathUrl + url;
                if (!StringUtils.isEmpty(httpPathDto.getPathParam())) {
                    //把它的环境变量放入
                    JSONObject beforeObj = JSONObject.parseObject(httpPathDto.getPathParam(), JSONObject.class);
                    Set<Map.Entry<String, Object>> entries = beforeObj.entrySet();
                    entries.forEach(entry -> header.put(entry.getKey(), entry.getValue().toString()));
                    RestTemplateUtils.setHeader(header);
                }
            }
        }

        List<JSONObject> json = new ArrayList<>();
        // 数据集不为空且 开关使用数据集 否则依旧使用页面body参数
        if (!StringUtils.isEmpty(dto.getDataSourceId()) && "0".equals(dto.getSwitchFlag())) {

            json = dataSetService.getParseData(dto.getDataSourceId());
        }

        List<String> tmps = new ArrayList<>();
        List<String> targetData = new ArrayList<>();


        //批次
        Integer batchCount = dto.getBatchCount();

        // 批次处理
        int totalItems = json.size();
        int startIndex = 0;

        if (null == batchCount || 0 == batchCount) {
            ResponseEntity<Object> result;
            String sendData = json.toString();
            //数据集为空则取页面参数
            if (StringUtils.isEmpty(sendData.replace("[", "").replace("]", ""))) {
                sendData = bodyJSONArray;
            }
            //java处理
            if (!CollectionUtils.isEmpty(httpTransform)) {
                List<HttpDataSetTransformDto> before = httpTransform.stream().filter(data -> data.getType() == 0).collect(Collectors.toList());
                sendData = dataSetTransformService.beforeHttpResultTransform(before, sendData).toString();
                //后置参数赋值
                httpTransform = httpTransform.stream().filter(data -> data.getType() == 1).collect(Collectors.toList());
            }

            switch (method) {
                case "GET":
                    result = RestTemplateUtils.request(url, HttpMethod.GET, params, sendData);
                    break;
                case "POST":
                    result = RestTemplateUtils.request(url, HttpMethod.POST, formData, sendData);
                    break;
                case "PUT":
                    result = RestTemplateUtils.request(url, HttpMethod.PUT, formData, sendData);
                    break;
                case "DELETE":
                    result = RestTemplateUtils.request(url, HttpMethod.DELETE, params, sendData);
                    break;
                default:
                    throw new RuntimeException("暂未支持\"" + method + "\"方法");
            }

            // 获取 HTTP 状态码
            int statusCode = result.getStatusCodeValue();

            // 获取响应体的大小
            String responseBody = result.getBody().toString();
            int responseBodySize = responseBody != null ? responseBody.getBytes().length : 0;

            response.setHeader("status", String.valueOf(statusCode));
            response.setHeader("responseBodySize", String.valueOf(responseBodySize));
            response.setStatus(statusCode);

            tmps.add(responseBody);

            JSONObject retuObj = new JSONObject();

            retuObj.put("result", responseBody);
            retuObj.put("requestData", sendData);
            retuObj.put("apiUrl", url);
            retuObj.put("method", method);


            if (!CollectionUtils.isEmpty(httpTransform)) {
                targetData.add(dataSetTransformService.httpResultTransform(httpTransform, retuObj.toJSONString()));
            }

            hashmap.put("originResponse", tmps);
            hashmap.put("targetData", targetData);


            return hashmap;
        }
        // 循环处理数据
        while (startIndex < totalItems) {
            // 计算批次的结束索引
            int endIndex = Math.min(startIndex + batchCount, totalItems);
            JSONArray batch = new JSONArray();

            // 获取每一批次的数据
            for (int i = startIndex; i < endIndex; i++) {
                batch.add(json.get(i));
            }
            if (batchCount == 1) {
                for (Object o : batch) {
                    JSONObject object = (JSONObject) o;
                    String sendData = object.toJSONString();
                    //java处理
                    if (!CollectionUtils.isEmpty(httpTransform)) {
                        List<HttpDataSetTransformDto> before = httpTransform.stream().filter(data -> data.getType() == 0).collect(Collectors.toList());
                        sendData = dataSetTransformService.beforeHttpResultTransform(before, sendData);
                        //后置参数赋值
                        httpTransform = httpTransform.stream().filter(data -> data.getType() == 1).collect(Collectors.toList());
                    }
                    // 发送该批次数据
                    ResponseEntity<Object> result;
                    switch (method) {
                        case "GET":
                            result = RestTemplateUtils.request(url, HttpMethod.GET, params, sendData);
                            break;
                        case "POST":
                            result = RestTemplateUtils.request(url, HttpMethod.POST, formData, sendData);
                            break;
                        case "PUT":
                            result = RestTemplateUtils.request(url, HttpMethod.PUT, formData, sendData);
                            break;
                        case "DELETE":
                            result = RestTemplateUtils.request(url, HttpMethod.DELETE, params, sendData);
                            break;
                        default:
                            throw new RuntimeException("暂未支持\"" + method + "\"方法");
                    }
                    String responseBody = result.getBody().toString();
                    tmps.add(responseBody);
                    JSONObject retuObj = new JSONObject();

                    retuObj.put("result", responseBody);
                    retuObj.put("requestData", sendData);
                    retuObj.put("apiUrl", url);
                    retuObj.put("method", method);


                    if (!CollectionUtils.isEmpty(httpTransform)) {
                        targetData.add(dataSetTransformService.httpResultTransform(httpTransform, retuObj.toJSONString()));
                    }
                }
            } else {
                String sendData = batch.toJSONString();
                //java处理
                if (!CollectionUtils.isEmpty(httpTransform)) {
                    List<HttpDataSetTransformDto> before = httpTransform.stream().filter(data -> data.getType() == 0).collect(Collectors.toList());
                    sendData = dataSetTransformService.beforeHttpResultTransform(before, sendData);
                    //后置参数赋值
                    httpTransform = httpTransform.stream().filter(data -> data.getType() == 1).collect(Collectors.toList());
                }
                // 发送该批次数据
                ResponseEntity<Object> result;
                switch (method) {
                    case "GET":
                        result = RestTemplateUtils.request(url, HttpMethod.GET, params, sendData);
                        break;
                    case "POST":
                        result = RestTemplateUtils.request(url, HttpMethod.POST, formData, sendData);
                        break;
                    case "PUT":
                        result = RestTemplateUtils.request(url, HttpMethod.PUT, formData, sendData);
                        break;
                    case "DELETE":
                        result = RestTemplateUtils.request(url, HttpMethod.DELETE, params, sendData);
                        break;
                    default:
                        throw new RuntimeException("暂未支持\"" + method + "\"方法");
                }
                String responseBody = result.getBody().toString();
                tmps.add(responseBody);
                JSONObject retuObj = new JSONObject();

                retuObj.put("result", responseBody);
                retuObj.put("requestData", sendData);
                retuObj.put("apiUrl", url);
                retuObj.put("method", method);


                if (!CollectionUtils.isEmpty(httpTransform)) {
                    targetData.add(dataSetTransformService.httpResultTransform(httpTransform, retuObj.toJSONString()));
                }

            }


            // 更新索引，准备下一批次
            startIndex = endIndex;
        }
        hashmap.put("originResponse", tmps);
        hashmap.put("targetData", targetData);

        return hashmap;
    }

    @Override
    public Object sendRequest(String httpId) {
        HashMap<Object, Object> hashmap = new HashMap<>();

        LambdaQueryWrapper<Http> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Http::getId, httpId);
        Http http = HttpMapper.selectOne(wrapper);
        System.err.println("定时任务发送====" + http.getHttpName());

        //是否解析处理结果
        List<HttpDataSetTransformDto> httpTransform = httpDataSetTransformService.getByHttpId(http.getId());

        //方法转大写
        String method = http.getMethod().toUpperCase();
        String url = http.getUrl();
        //菜单栏 请求头 参数
        String menus = http.getMenus();
        JSONObject jsonObject = JSONObject.parseObject(menus);

        //获取请求头
        JSONObject headers = jsonObject.getJSONObject("headers");
        Map<String, String> header = new HashMap<>();
        if (!CollectionUtils.isEmpty(headers)) {
            headers.forEach((key, value) -> header.put(key, value.toString()));
            RestTemplateUtils.setHeader(header);
        }

        JSONObject params = jsonObject.getJSONObject("params");


        //获取body参数
        JSONObject body = jsonObject.getJSONObject("body");
        //formdata
        JSONObject formData = body.getJSONObject("formData");
        //body中的json参数
        String bodyJSONArray = body.getString("json");

        //加入前置url拼接和请求头拼接
        if (!StringUtils.isEmpty(http.getHttpPathId())) {
            HttpPathDto httpPathDto = httpPathService.getById(http.getHttpPathId());
            if (!Objects.isNull(httpPathDto)) {
                String pathUrl = httpPathDto.getPathUrl();
                //加上前置http://xxx.com
                url = pathUrl + url;
                if (!StringUtils.isEmpty(httpPathDto.getPathParam())) {
                    //把它的环境变量放入
                    JSONObject beforeObj = JSONObject.parseObject(httpPathDto.getPathParam(), JSONObject.class);
                    Set<Map.Entry<String, Object>> entries = beforeObj.entrySet();
                    entries.forEach(entry -> header.put(entry.getKey(), entry.getValue().toString()));
                    RestTemplateUtils.setHeader(header);
                }
            }
        }

        List<JSONObject> json = new ArrayList<>();
        // 数据集不为空且 开关使用数据集 否则依旧使用页面body参数
        if (!StringUtils.isEmpty(http.getDataSourceId()) && "0".equals(http.getSwitchFlag())) {

            json = dataSetService.getParseData(http.getDataSourceId());
        }

        List<String> tmps = new ArrayList<>();
        List<String> targetData = new ArrayList<>();
        //批次
        Integer batchCount = http.getBatchCount();

        // 批次处理
        int totalItems = json.size();
        int startIndex = 0;

        if (null == batchCount || 0 == batchCount) {
            ResponseEntity<Object> result;
            String sendData = json.toString();
            //数据集为空则取页面参数
            if (StringUtils.isEmpty(sendData.replace("[", "").replace("]", ""))) {
                sendData = bodyJSONArray;
            }
            //java处理
            if (!CollectionUtils.isEmpty(httpTransform)) {
                List<HttpDataSetTransformDto> before = httpTransform.stream().filter(data -> data.getType() == 0).collect(Collectors.toList());
                sendData = dataSetTransformService.beforeHttpResultTransform(before, sendData);
                //后置参数赋值
                httpTransform = httpTransform.stream().filter(data -> data.getType() == 1).collect(Collectors.toList());
            }
            switch (method) {
                case "GET":
                    result = RestTemplateUtils.request(url, HttpMethod.GET, params, sendData);
                    break;
                case "POST":
                    result = RestTemplateUtils.request(url, HttpMethod.POST, formData, sendData);
                    break;
                case "PUT":
                    result = RestTemplateUtils.request(url, HttpMethod.PUT, formData, sendData);
                    break;
                case "DELETE":
                    result = RestTemplateUtils.request(url, HttpMethod.DELETE, params, sendData);
                    break;
                default:
                    throw new RuntimeException("暂未支持\"" + method + "\"方法");
            }

            // 获取响应体的大小
            String responseBody = result.getBody().toString();

            tmps.add(responseBody);
            JSONObject retuObj = new JSONObject();

            retuObj.put("result", responseBody);
            retuObj.put("requestData", sendData);
            retuObj.put("apiUrl", url);
            retuObj.put("method", method);
            System.err.println("responseBody:" + responseBody);
            if (!CollectionUtils.isEmpty(httpTransform)) {
                targetData.add(dataSetTransformService.httpResultTransform(httpTransform, retuObj.toJSONString()));
            }

            hashmap.put("originResponse", tmps);
            hashmap.put("targetData", targetData);

            return hashmap;
        }

        while (startIndex < totalItems) {
            int endIndex = Math.min(startIndex + batchCount, totalItems);
            JSONArray batch = new JSONArray();

            // 获取每一批次的数据
            for (int i = startIndex; i < endIndex; i++) {
                batch.add(json.get(i));
            }
            if (batchCount == 1) {
                for (Object o : batch) {
                    JSONObject object = (JSONObject) o;
                    String sendData = object.toJSONString();
                    //java处理
                    if (!CollectionUtils.isEmpty(httpTransform)) {
                        List<HttpDataSetTransformDto> before = httpTransform.stream().filter(data -> data.getType() == 0).collect(Collectors.toList());
                        sendData = dataSetTransformService.beforeHttpResultTransform(before, sendData);
                        //后置参数赋值
                        httpTransform = httpTransform.stream().filter(data -> data.getType() == 1).collect(Collectors.toList());
                    }

                    // 发送该批次数据
                    ResponseEntity<Object> result;
                    switch (method) {
                        case "GET":
                            result = RestTemplateUtils.request(url, HttpMethod.GET, params, sendData);
                            break;
                        case "POST":
                            result = RestTemplateUtils.request(url, HttpMethod.POST, formData, sendData);
                            break;
                        case "PUT":
                            result = RestTemplateUtils.request(url, HttpMethod.PUT, formData, sendData);
                            break;
                        case "DELETE":
                            result = RestTemplateUtils.request(url, HttpMethod.DELETE, params, sendData);
                            break;
                        default:
                            throw new RuntimeException("暂未支持\"" + method + "\"方法");
                    }

                    String responseBody = result.getBody().toString();

                    tmps.add(responseBody);
                    JSONObject retuObj = new JSONObject();

                    retuObj.put("result", responseBody);
                    retuObj.put("requestData", sendData);
                    retuObj.put("apiUrl", url);
                    retuObj.put("method", method);
                    System.err.println("responseBody:" + responseBody);
                    if (!CollectionUtils.isEmpty(httpTransform)) {
                        targetData.add(dataSetTransformService.httpResultTransform(httpTransform, retuObj.toJSONString()));
                    }

                }
            } else {
                String sendData = batch.toJSONString();
                //java处理
                if (!CollectionUtils.isEmpty(httpTransform)) {
                    List<HttpDataSetTransformDto> before = httpTransform.stream().filter(data -> data.getType() == 0).collect(Collectors.toList());
                    sendData = dataSetTransformService.beforeHttpResultTransform(before, sendData);
                    //后置参数赋值
                    httpTransform = httpTransform.stream().filter(data -> data.getType() == 1).collect(Collectors.toList());
                }

                // 发送该批次数据
                ResponseEntity<Object> result;
                switch (method) {
                    case "GET":
                        result = RestTemplateUtils.request(url, HttpMethod.GET, params, sendData);
                        break;
                    case "POST":
                        result = RestTemplateUtils.request(url, HttpMethod.POST, formData, sendData);
                        break;
                    case "PUT":
                        result = RestTemplateUtils.request(url, HttpMethod.PUT, formData, sendData);
                        break;
                    case "DELETE":
                        result = RestTemplateUtils.request(url, HttpMethod.DELETE, params, sendData);
                        break;
                    default:
                        throw new RuntimeException("暂未支持\"" + method + "\"方法");
                }

                String responseBody = result.getBody().toString();

                tmps.add(responseBody);
                JSONObject retuObj = new JSONObject();

                retuObj.put("result", responseBody);
                retuObj.put("requestData", sendData);
                retuObj.put("apiUrl", url);
                retuObj.put("method", method);
                System.err.println("responseBody:" + responseBody);
                if (!CollectionUtils.isEmpty(httpTransform)) {
                    targetData.add(dataSetTransformService.httpResultTransform(httpTransform, retuObj.toJSONString()));
                }
            }


            // 更新索引，准备下一批次
            startIndex = endIndex;
        }
        hashmap.put("originResponse", tmps);
        hashmap.put("targetData", targetData);

        return hashmap;
    }

    @Override
    public List<HttpDto> queryByDirId(String dirId) {
        LambdaQueryWrapper<Http> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Http::getDirId, dirId);
        wrapper.orderByAsc(Http::getSort);
        List<Http> https = HttpMapper.selectList(wrapper);
        List<HttpDto> lists = new ArrayList<>();

        if (!CollectionUtils.isEmpty(https)) {
            for (Http http : https) {
                HttpDto httpDto = new HttpDto();
                BeanUtils.copyProperties(http, httpDto);
                List<HttpDataSetTransformDto> dataSet = httpDataSetTransformService.getByHttpId(http.getId());
                httpDto.setHttpDataSetTransformDtoList(dataSet);
                lists.add(httpDto);
            }
        } else {
            for (Http http : https) {
                HttpDto httpDto = new HttpDto();
                BeanUtils.copyProperties(http, httpDto);
                lists.add(httpDto);
            }
        }

        return lists;
    }

    @Override
    public List<Http> queryAllQuartz() {
        LambdaQueryWrapper<Http> wrapper = new LambdaQueryWrapper<>();
        wrapper.isNull(Http::getQuartzId);
        return HttpMapper.selectList(wrapper);
    }


    private Http copyDataSet(Http dataSet) {
        //复制主表数据
        Http copyDataSet = new Http();
        GaeaBeanUtils.copyAndFormatter(dataSet, copyDataSet);
        copyDataSet.setId(null);
        return copyDataSet;
    }

}
